import React from 'react'
import { useNavigate } from 'react-router-dom'
// 引入from 表单
import {
    Form,
    Input,
    Button,
    Toast
} from 'antd-mobile'
import { connect } from 'react-redux'

import { loginApi, getAuthCode, getUserInfo } from '../../api'
import { loginType, axiosResponseConfigType, storeType } from '../../interface'

const  Login = (props: storeType) => {

    const navigate = useNavigate()

    const onFinish = (e: loginType) => {
        loginApi(e).then((res: axiosResponseConfigType) => {
            const { token } = res

            // 将token 保存到本地
            localStorage.setItem('token', token as string)

            // 获取用户信息
            getUserInfo().then((res: axiosResponseConfigType) => {
                const { dispatch } = props

                dispatch({type: 'CHANGE_USER_INFO', data: res.data})

                navigate('/')
            })


        })
    }

    // 获取短信验证码
    const getCode = () => {
        getAuthCode().then((res: axiosResponseConfigType) => {
            Toast.show({ content: res.data })
        })
    }


    return (
        <div>
            <Form
                onFinish={onFinish}
                footer={
                    <Button block type='submit' color='primary'>
                        提交
                    </Button>
                }
            >
                <Form.Item
                    name='username'
                    label='手机号'
                    // 校验
                    rules={[{ required: true, message: '手机号' }]}
                >
                    <Input placeholder='请输入账号' />
                </Form.Item>


                <Form.Item
                    label='短信验证码'
                    name='code'
                    extra={<Button onClick={() => getCode()}>发送验证码</Button>}
                    rules={[{ required: true, message: '密码不能为空' }]}
                >
                    <Input placeholder="请输入短信验证码" />
                </Form.Item>

            </Form>
        </div>
    )
}

const mapStateToProps = (state:any) => state

export default connect(mapStateToProps)(Login)
